import Access from '@/components/Access';
import HandleBtn from '@/components/HandleBar/btn';
import { ModalForm, ProColumns, ProTable } from '@/components/Pro';
import { TenantryType } from '@/pages/System/TenantryManager/type';
import {
  versionManageControllerDeleteBatch,
  versionManageControllerList,
} from '@/services/ess/upgradeVersion';
import { fetchDictInfo } from '@/utils';
import { message, Modal, Space } from 'antd';
import type { TableRowSelection } from 'antd/lib/table/interface';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { useIntl } from 'umi';
import Styles from '../index.less';
import AddModal from './components/AddModal';

const VersionManagement: React.FC = () => {
  const [initTypeOption, setInitOption] = useState([]);
  let [dictOption, setDictOption] = useState([]);
  const { confirm } = Modal;
  const { success, warning } = message;
  const [selectedColumns, setSelectedColumns] = useState<string[]>([]);
  const tableActionRef = useRef(null);
  const intl = useIntl();
  const isEnglish = intl.locale === 'en-US';
  const submitSuccess = (token: boolean) => {
    if (token) {
      tableActionRef?.current?.reload();
    }
  };
  const tableColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.SN' }),
      dataIndex: 'NO',
      key: 'NO',
      valueType: 'index',
      width: 60,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.deviceType' }),
      dataIndex: 'deviceType',
      key: 'deviceType',
      valueType: 'select',
      fieldProps: {
        value: initTypeOption,
        mode: 'multiple',
        maxTagCount: 2,
        onChange: (value) => {
          setInitOption(value);
        },
      },
      request: async () => {
        return await fetchDictInfo(100009);
      },
      search: {
        transform: (value) => {
          return {
            deviceType: value,
          };
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.deviceModel' }),
      dataIndex: 'deviceModel',
      key: 'deviceModel',
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.upgradePackage' }),
      dataIndex: 'packageName',
      key: 'packageName',
      width: 180,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.uploadTime' }),
      dataIndex: 'createTime',
      initialValue: [dayjs().subtract(6, 'day'), dayjs()],
      valueType: 'dateRange',
      width: 150,
      render: (_, record) => {
        return <span>{record.createTime}</span>;
      },
      search: {
        transform: (value) => {
          return {
            createStartTime: value[0],
            createEndTime: value[1],
          };
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.versionNumber' }),
      dataIndex: 'version',
      key: 'version',
      hideInSearch: true,
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.operation' }),
      dataIndex: 'operation',
      key: 'operation',
      hideInSearch: true,
      width: 140,
      render: (_, record) => {
        return [
          <Space key="operation">
            <Access perm={'remote:version:upload'} key={'download'}>
              <a href={record.path}>
                {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.download' })}
              </a>
            </Access>
            <Access perm={'remote:version:edit'} key={'addModal'}>
              <AddModal formProps={record} isEdit={true} submitSuccess={submitSuccess} />
            </Access>
            <Access perm={'remote:version:del'} key={'delete'}>
              <a
                className="global-del-color"
                onClick={() => {
                  console.log('record', record);
                  confirm({
                    title: '提示',
                    content: '数据删除后将不可恢复，是否删除？',
                    onOk() {
                      versionManageControllerDeleteBatch([record.recordId]).then((res) => {
                        console.log('versionManageControllerDeleteBatch', res);
                        if (res.success) {
                          tableActionRef?.current?.reload();
                          success(res.message);
                        }
                      });
                    },
                  });
                }}
              >
                {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.delete' })}
              </a>
            </Access>
          </Space>,
        ];
      },
    },
  ];

  const selectionChange = (_: React.Key[], selectedRows: API.SysTenant[]) => {
    const tempArray: string[] = [];
    selectedRows.forEach((item: any) => {
      tempArray.push(item.recordId as string);
    });
    setSelectedColumns(tempArray);
  };
  const handleRowSelection: TableRowSelection<TenantryType> = {
    onChange: selectionChange,
  };
  // const handleUpload = (file: RcFile) => {
  //   console.log('Uploading file', file);
  //   versionManageControllerUpload(file).then((result) => {
  //     console.log('Upload complete', result);
  //   });
  // };
  useEffect(() => {
    fetchDictInfo(100009).then((res) => {
      const option = res.map((item) => {
        return item.value;
      });

      setInitOption(option);
      setDictOption(option);
    });
  }, []);
  return (
    <>
      <ProTable
        onReset={async () => {
          setInitOption(dictOption);
        }}
        actionRef={tableActionRef}
        rowSelection={handleRowSelection}
        rowKey={'pageIndex'}
        headerTitle={
          <div className={`${isEnglish ? Styles.table_header_title : ''}`}>
            {intl.formatMessage({
              id: 'remoteUpgradeMangment.versionManagement.versionManagement',
            })}
          </div>
        }
        request={async (values) => {
          const params = {
            ...values,
            deviceType: initTypeOption.join(','),
          };
          return await versionManageControllerList(params);
        }}
        columns={tableColumns}
        toolBarRender={() => [
          <Access perm={'remote:version:add'} key={'addModal'}>
            <AddModal key="addModal" isEdit={false} submitSuccess={submitSuccess} />
          </Access>,
          // <Upload
          //   key="upload"
          //   beforeUpload={(file: RcFile) => {
          //     handleUpload(file);
          //   }}
          // >
          //   <HandleBtn handleType="import">上传软件包</HandleBtn>
          // </Upload>,
          <Access perm={'remote:version:del'} key={'delete'}>
            <HandleBtn
              key="delete"
              handleType="delete"
              onClick={() => {
                if (selectedColumns.length === 0) {
                  warning(
                    intl.formatMessage({
                      id: 'remoteUpgradeMangment.requiredFields.leastOne',
                    }),
                  );
                  return false;
                }
                confirm({
                  title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
                  content: intl.formatMessage({
                    id: 'systemManagement.supplementary.dataCannotBeRestoredAfterDeletion',
                  }),
                  onOk() {
                    versionManageControllerDeleteBatch(selectedColumns).then((res) => {
                      console.log('versionManageControllerDeleteBatch', res);
                      if (res.success) {
                        tableActionRef?.current?.reload();
                        success(res.message);
                      }
                    });
                  },
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDelete' })}
            </HandleBtn>
          </Access>,
        ]}
      ></ProTable>
      <ModalForm></ModalForm>
    </>
  );
};

export default VersionManagement;
